package zuosheng.day5;

/**
 * @author lj
 * @Description: 转圈打印矩阵
 * @date 2020-11-04 21:49
 * @QQ 851477108
 */


public class PrintMatrixSpiralOrder {
    public static void main(String[] args) {
        int[][] matrix = {{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } };
        spiralOrderPrint(matrix);
    }
    public static void spiralOrderPrint(int[][] m){
        int tR = 0;
        int tC = 0;
        int dR = m.length - 1;
        int dC = m[0].length - 1;
        while (tR <= dR && tC <= dC){
            printEdge(m,tR++,tC++,dR--,dC--);
        }
    }

    public static void printEdge(int[][] m,int tR,int tC,int dR,int dC){
        if (tR == dR){
            //子矩阵只有一行
            for (int i = tC; i <= dC; i++){
                System.out.print(m[tR][i]+" ");
            }
        }else if (tC == dC){
            //子矩阵只有一列
            for (int i = 0; i < dR; i++) {
                System.out.print(m[i][tC]+" ");
            }
        }else {//一般情况,循环打印
            int tempC = tC;
            int tempR = tR;
            while (tempC!=dC){
                //顺时针右
                System.out.print(m[tR][tempC++]+" ");
            }
            while (tempR!=dR){
                //下
                System.out.print(m[tempR++][dC]+" ");
            }
            while (tempC!=tC){
                //左
                System.out.print(m[dR][tempC--]+" ");
            }
            while (tempR!=tR){
                //上
                System.out.print(m[tempR--][tC]+" ");
            }
        }
    }
}
